<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> 批量上传 </title>
</head>
<body>
<!--<script src="./jquery-1.11.3.js"></script>-->
<script src="http://192.168.0.254/test/up/jquery-1.11.3.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

<div class="login_frame" style="position:relative";>
    <div class="login_gl" style="margin-top:10px;">
        <div id="msgdiv"></div>
    </div>

    <div class="login_gl" style="margin-top:10px;">
        <span class="login_wz" >登录</span>
    </div>

    <div class="login_gl" style="margin-top:10px;">
        <input id="loginid" name="loginid" type="text" placeholder="请输入您的用户名" value="Rick"/>
    </div>
    <div class="login_gl" style="margin-top:10px;">
        <input id="password" name="password" type="password" placeholder="请输入您的密码" value="665544" />
    </div>
    <div class="login_gl" style="margin-top:10px;">
        <button  id="login_btn" style="font-size:16px;">登录</button>
    </div>

    <div class="login_gl" style="margin-top:10px;display:none;">
        <button  id="test1" style="font-size:16px;">test1</button>
    </div>
    <div class="login_gl" style="margin-top:10px;display:none;">
        <button  id="test2" style="font-size:16px;">test2</button>
    </div>
    <div class="login_gl" style="margin-top:10px;display:none;">
        <button  id="nologintips" style="font-size:16px;">nologintips</button>
    </div>
    <div class="login_gl" style="margin-top:20px;">
        <form id="infoLogoForm" enctype='multipart/form-data'>
            <div class="cnt-updateWrapper" >
                <div>
                    <div id="loadImg" class="cnt-img-content" >
                        <div id="licenseBox" class="ctn-licence">
                            选择要上传的图片
                            <input type="file" id="selectFile" name="file" accept="image/*"  multiple="multiple"   style="height:40px">
                        </div>
                        <div>
                            <button id="doUpload" class="btn btn-default cnt-save" type="button" disabled="false">上传</button>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
    <div>
        点击上传图片之后将可用的通过
        <a href="http://api.shoukaiseki.top:8182/module/connector/uniqueid/431/" target="_blank">图片上传</a>
        接口进行上传,全部上传完成后调用
        <a href="http://api.shoukaiseki.top:8182/module/connector/uniqueid/741/" target="_blank">更新SKU对应图片</a>
        接口
    </div>
    <div id="dialog" title="图片批量上传,命名方式[商品编号-颜色]" width="500px" >
        <table id="table">
            <tr>
                <th width="30px">可用</th>
                <th width="200px">文件名</th>
                <th width="50px">大小</th>
                <th width="20px">比例</th>
                <th>对应商品</th>
                <th>商品颜色</th>
                <th>图片</th>
                <th>错误信息</th>
            </tr>
        </table>
        <button id="dialog_ok" style="font-size:16px;">上传可用图片</button>
    </div>
</div>


</div>
<script type="text/javascript">
    var domainUrl="http://192.168.0.200:15000";

    $.ajaxSetup({
        global: false,
        // 允许携带证书,添加之后跨域跳转页面失败
        xhrFields: {
            withCredentials: true
        },
        // // 允许跨域
        crossDomain: true,
        complete: function(XMLHttpRequest, textStatus){
            // console.log("XMLHttpRequest=",XMLHttpRequest);
            // console.log("XMLHttpRequest.json=",JSON.stringify(XMLHttpRequest));
            // console.log("textStatus=",textStatus);
        }
    });

    var uploading = false;

    $("#doUpload").click(function () {
        $("#doUpload").attr('disabled',true);

        // $("#logo").attr("src",getObjectURL($('#infoLogoForm')[0]));
        if(uploading){
            alert("文件正在上传中，请稍候");
            return false;
        }
        $.ajax({
            url: domainUrl + "/sys/image/uploadImage",
            type: 'POST',
            cache: false,
            data: new FormData($('#infoLogoForm')[0]),
            processData: false,
            contentType: false,
            dataType:"json",
            beforeSend: function(){
                uploading = true;
            },
            success : function(msg) {
                uploading = false;
                console.log(msg);
                $("#msgdiv").text(JSON.stringify(msg));
            }
        });
    });

    var tableData={};

    function clearTable(){
        $("#table tr:not(:first)").empty();
        tableData={};
    }

    /**
     * 为table指定行添加一行
     *
     * tab 表id
     * row 行数，如：0->第一行 1->第二行 -2->倒数第二行 -1->最后一行
     * trHtml 添加行的html代码
     *
     */
    function addFile(index,file){
        var filename=file.name;
        var fileSize=file.size;
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function(theFile) {
            var image = new Image();
            image.src = theFile.target.result;
            image.onload = function() {
                var bili= (this.height/(this.width/16)).toFixed(0);
                var verification=true;
                var msg=[];
                if(bili!=9){
                    verification=false;
                    msg.push("比例不为16:9");
                }
                if(fileSize>(200*1024)){
                    verification=false;
                    msg.push("大于200K");
                }
                if(fileSize>(1024*1024)){
                    fileSize=(fileSize/1024/1024).toFixed(2)+"MB";
                }else {
                    fileSize=(fileSize/1024).toFixed(2)+"KB";
                }
                var namePrefix = filename.substring(0, filename.indexOf("."));
                var strings = namePrefix.split("-");
                console.log("strings=",strings);
                pdProductId=-1;
                pdName="";
                pdColor="";
                productNumber="";
                skuUniqueCodeList=[];
                if(strings.length<2){
                    verification=false;
                    msg.push("文件命名不规范");
                }else{
                    pdProductId=strings[0];
                    pdColor=strings[1];
                }

                if(verification){
                    var formdata = new FormData();
                    formdata.append("productId",pdProductId);
                    formdata.append("skuColor",pdColor);
                    //ajax去服务器端校验

                    $.ajax({
                        type:"POST",
                        url:domainUrl+"/image/product/verifyImage",
                        data:formdata,
                        processData:false,
                        contentType:false,
                        dataType:'json',
                        async: false,
                        success:function(result,textStatus, request){
                            console.log("msg=",result);
                            if(result.status==0){
                                pdName=result.data.pdName;
                                productNumber=result.data.productNumber;
                                skuUniqueCodeList=result.data.skuUniqueCodeList;
                                tableData[productNumber]={
                                    "productNumber":productNumber,
                                    "pdName":pdName,
                                    "skuUniqueCodeList":skuUniqueCodeList
                                }
                            }else{
                                verification=false;
                                msg.push(result.statusParams);
                            }
                        }
                    });
                }

                selectChecked='';
                if(verification==true){
                    selectChecked="checked";
                    console.log("verification=true",verification)
                }else{
                    console.log("verification=false",verification)
                }
                // alert("图片的宽度为"+this.width+",长度为"+this.height);
                //获取table最后一行 $("#tab tr:last")
                //获取table第一行 $("#tab tr").eq(0)
                //获取table倒数第二行 $("#tab tr").eq(-2)
                var trHtml='' +
                    '<tr align="center">' +
                        '<td > <input id="select_img_'+index+'" data-product-number="'+productNumber+'" type="checkbox" '+selectChecked+' disabled/></td>' +
                        '<td >' + filename+ '</td>' +
                        '<td >'+fileSize+'</td>' +
                        '<td >16:'+bili+'</td>' +
                        '<td >'+pdName+'</td>' +
                        '<td >'+pdColor+'</td>' +
                        '<td ><img id="upload_img_'+index+'" style="height:100px;" src="" /></td>' +
                        '<td >'+msg+'</td>' +
                    '</tr>';
                var $tr=$("#table tr:last");
                $tr.after(trHtml);
                var readFile = new FileReader();
                readFile.readAsDataURL(file);
                readFile.onload = function() {
                    var img = $("#upload_img_"+index);
                    img.attr("src", this.result);
                }
            };
        };
    }


    $("#selectFile").on("change", function(){
        console.log($("#selectFile")[0]);
        var readFile = new FileReader();
        var mfile = $("#selectFile")[0].files;
        console.log(mfile);
        if(mfile != undefined && mfile.length>0){
            $("#dialog").dialog({width: 1000});
            clearTable();
            for(var i=0;i<mfile.length;i++){
                var file=mfile[i];
                console.log(file);
                addFile(i,file);
                // readFile.readAsDataURL(mfile);
                // readFile.onload = function() {
                //     var img = $("#logo");
                //     img.attr("src", this.result);
                //     $("#doUpload").attr('disabled',false);
                // }
            }
        }else {
            //如果点击'选择文件后取消,则不让上传,否则上传的是个空文件'
            $("#doUpload").attr('disabled',true);
        }
    });

    $("#login_btn").click(function(){
        $("#msgdiv").text("登录中...如果一直显示该字符请查看浏览器console");
        var formdata = new FormData();
        var loginid = $.trim($("#loginid").val());
        var password = $.trim($("#password").val());
        if(loginid == ""){
            alert("请输入用户名");
            return false;
        }else if(password == ""){
            alert("请输入密码");
            return false;
        }
        formdata.append("userName",loginid);
        formdata.append("password",password);
        //ajax去服务器端校验

        $.ajax({
            type:"POST",
            url:domainUrl+"/login",
            data:formdata,
            processData:false,
            contentType:false,
            dataType:'json',
            // async: false,
            success:function(msg,textStatus, request){
                console.log(request);
                console.log(sessionStorage);
                console.log("cookie",document.cookie)
                // var jsessionid= sessionStorage.getItem("JSESSIONID");
                //  console.log("jsessionid="+jsessionid);
                //   jsessionid= sessionStorage.getItem("access_token");
                //  console.log("jsessionid="+jsessionid);
                $("#msgdiv").text(JSON.stringify(msg));
                console.log(msg);
            }
        });
    });

    $("#test1").click(function(){
        //ajax去服务器端校验
        $("#msgdiv").text("处理中...如果一直显示该字符请查看浏览器console");


        $.ajax({
            type:"POST",
            url:domainUrl+"/authc/list",
            processData:false,
            contentType:false,
            dataType:'json',
            success:function(msg){
                $("#msgdiv").text(JSON.stringify(msg));
            },
            error:function(response, ajaxOptions, thrownError){
                console.log("response=",response);
                console.log("ajaxOptions=",ajaxOptions);
                console.log("thrownError=",thrownError);
                $("#msgdiv").text(JSON.stringify(response));
            }
        });
    });

    $("#test2").click(function(){
        //ajax去服务器端校验
        $("#msgdiv").text("处理中...如果一直显示该字符请查看浏览器console");


        $.ajax({
            type:"POST",
            url:domainUrl+"/test2",
            processData:false,
            contentType:false,
            dataType:'json',
            success:function(msg){
                $("#msgdiv").text(JSON.stringify(msg));
            },
            error:function(response, ajaxOptions, thrownError){
                console.log("response=",response);
                console.log("ajaxOptions=",ajaxOptions);
                console.log("thrownError=",thrownError);
                $("#msgdiv").text(JSON.stringify(response));
            }
        });
    });

    $("#nologintips").click(function(){
        //ajax去服务器端校验
        $("#msgdiv").text("处理中...如果一直显示该字符请查看浏览器console");

        $.ajax({
            type:"POST",
            url:domainUrl+"/nologintips",
            processData:false,
            contentType:false,
            dataType:'json',
            success:function(msg){
                $("#msgdiv").text(JSON.stringify(msg));
            }
        });
    });

    $("#dialog_ok").click(function () {

        var mfile = $("#selectFile")[0].files;
        if(mfile != undefined && mfile.length>0){
            for(var i=0;i<mfile.length;i++){
                var si = $("#select_img_"+i);
                console.log("si=",si,si.is(':checked'));
                var productNumber = si.data("product-number");
                console.log( productNumber);
                var product = tableData[productNumber];
                console.log(product);


            }

        }
    });


    $("#dialog").hide();
</script>
</body>